package com.example.demo.netty.server.handler;

import com.example.demo.netty.protocol.model.data.modBusData;
import com.example.demo.netty.util.SessionUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName modBusDataHandler
 * @Description
 * @Company inspur
 * @Author Kevin
 * @Date 2020/7/13 22:21
 * @Version 1.0
 */
@Slf4j
public class modBusDataHandler  extends SimpleChannelInboundHandler<modBusData> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, modBusData msg) throws Exception {
        log.info("收到客户端数据……");

        //取出数据
        byte address = msg.getAddress();

        //存数据库

        //检查客户端是否已连接，就是channel是否加入了map  ( 键为address )
        if (SessionUtil.equipmentChannelMap.get(msg.getAddress()) == null) {
            SessionUtil.equipmentChannelMap.put(msg.getAddress(), ctx);
        }
    }

    /**
     * 客户端主动断开服务端的链接,关闭流
     * */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().localAddress().toString() + " 通道不活跃！");
        removeChannnelMap(ctx);
        // 关闭流
        ctx.close();
    }

    /**
     * 发生异常处理
     * */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        // logger.error("连接异常,连接异常："+ DateUtils.dateToString(new Date())+cause.getMessage(), cause);
        ctx.fireExceptionCaught(cause);
        //   removeChannnelMap(ctx);
        //  ctx.close();
    }

    /**
     *删除map中ChannelHandlerContext
     *  */
    private void removeChannnelMap(ChannelHandlerContext ctx) {
        for (Byte key: SessionUtil.equipmentChannelMap.keySet()) {
            if (SessionUtil.equipmentChannelMap.get(key) != null && SessionUtil.equipmentChannelMap.get(key).equals(ctx)) {
                SessionUtil.equipmentChannelMap.remove(key);
            }
        }
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        super.userEventTriggered(ctx, evt);
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state().equals(IdleState.READER_IDLE))
                ctx.close();
            //标志该链接已经close 了 
        }
    }



}
